﻿using Furion;
using Furion.DatabaseAccessor;
using Furion.Schedule;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TulingMember.Core;

namespace TulingMember.Application
{
    public class JobService : IJob
    {

        private readonly ILogger<JobService> _logger;
        private readonly IRepository<cts_Customer> _customerRepository;
        private readonly IRepository<cts_CustomerPayLog> _customerpaylogRepository;
        public JobService(ILogger<JobService> logger
            , IRepository<cts_Customer> customerRepository
            , IRepository<cts_CustomerPayLog> customerpaylogRepository)
        {
            _logger = logger;
            _customerRepository = customerRepository;
            _customerpaylogRepository = customerpaylogRepository;
        }
        private static int Balance = App.GetConfig<int>("Common:Balance");

        public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
        {
            if (context.Trigger.NumberOfRuns == 3)
            {
                _logger.LogInformation("假装出错");
            }
            this.ResetCustomerBalance();
            _logger.LogInformation(context.ConvertToJSON());
            await Task.CompletedTask;
        }
        /// <summary>
        /// 修改余额
        /// </summary>
        /// <returns></returns>
        private void ResetCustomerBalance()
        {
            _logger.LogInformation("开始执行");
            //var customer = _customerRepository.Where(m => !m.IsDeleted && m.Name == "王鹏");
            //List<cts_CustomerPayLog> customerPayLogList = new List<cts_CustomerPayLog>();
            //foreach (cts_Customer cus in customer)
            //{
            //    cts_CustomerPayLog cts_CustomerPayLog = new cts_CustomerPayLog();
            //    cts_CustomerPayLog.CustomerId = cus.Id;
            //    cts_CustomerPayLog.CustomerName = cus.Name;
            //    cts_CustomerPayLog.ChangeAmount = Balance - cus.Balance;
            //    cts_CustomerPayLog.OldAmount = cus.Balance;
            //    cts_CustomerPayLog.NewAmount = Balance;
            //    cts_CustomerPayLog.OrderDate = DateTime.Now.Date;
            //    cts_CustomerPayLog.Remark = "账目重置";
            //    cus.Balance = Balance;
            //    customerPayLogList.Add(cts_CustomerPayLog);
            //}
            //_customerRepository.UpdateAsync(customer);
            //_customerpaylogRepository.InsertAsync(customerPayLogList);
            _logger.LogInformation("重置成功");
        }
    }
}
